Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
"Toggle" navigation with animation on scroll

I'm writing a code which will hide my navbar on scroll and display it again accordingly.
So far it works well, but I was curious on how implement some animation or transition to reveal/hide that element.

Here's my code so far

var prevScrollpos = window.pageYOffset;

window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("bottom-navigation").style.bottom = "0";    
  } else {
    document.getElementById("bottom-navigation").style.bottom = "-100px";
  }
  prevScrollpos = currentScrollPos;
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

  • Use CSS transform and transition which (in contrast to other properties like bottom top etc) can be GPU accelerated
  • Use a special class like i.e: .hidden or .hide than, all you need in JavaScript is a Element.classList.toggle(className, boolean) to toggle that class
  • Never use on(eventname)- unless you're creating brand new elements from in-memory.
    on* will override any previously added eventname to that element. Use a cumulative approach instead, by using Element.addEventListener()

const EL_bottomNav = document.querySelector("#bottom-navigation");

let prevScrollpos = window.pageYOffset;

const toggleBottomNav = () => {
  EL_bottomNav.classList.toggle("hide", prevScrollpos <= window.pageYOffset);
  prevScrollpos = window.pageYOffset;
};

// Do immediately:
// toggleBottomNav();

// And on page scroll:
window.addEventListener("scroll", toggleBottomNav);
/* QuickReset */ * {margin:0; box-sizing: border-box; }

body {
  min-height: 300vh; /* just to force some scrollbars */
}

#bottom-navigation {
  position: fixed;
  width: 100%;
  bottom:0;
  background: gold;
  padding: 30px;
  transition: 0.5s;
}

#bottom-navigation.hide {
  transform: translateY(100%);
}
Scroll down and than up
<footer id="bottom-navigation">I'm the bottom nav!</footer>

Nota bene:
Since Events added on scroll are expensive, don't query the DOM for your Element. Cache it beforehand instead (like in the example above). Also a throttle function would be helpful to leverage the load of function calls passed to the event loop in main thread.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!